package com.example.demo.conf;

import com.dtflys.forest.exceptions.ForestRuntimeException;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.http.ForestResponse;
import com.dtflys.forest.interceptor.Interceptor;
import com.dtflys.forest.reflection.ForestMethod;
import com.example.demo.entity.User;
import com.example.demo.exception.BaseException;


/*
 * @Description  HTTP请求的拦截器
 * @Date 10:23 2021/4/20
 * http://forest.dtflyx.com/docs/adv/interceptor
 **/
public class HttpSimpleInterceptor implements Interceptor<Object> {

    /**
     * 该方法在被调用时，并在beforeExecute前被调用
     *
     * @Param request Forest请求对象
     * @Param args 方法被调用时传入的参数数组
     */
    @Override
    public void onInvokeMethod(ForestRequest request, ForestMethod method, Object[] args) {

    }

    /**
     * 该方法在请求发送之前被调用, 若返回false则不会继续发送请求
     *
     * @Param request Forest请求对象
     */
    @Override
    public boolean beforeExecute(ForestRequest request) {
        // 执行在发送请求之前处理的代码
        // 添加Header
        request.addHeader("Type", "application/json");
        request.addHeader("zftsl", "136fe6736b751b3f44b09162af9a2e17");
        request.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat");
//        request.addHeader("Referer", "https://servicewechat.com/wx2c7f0f3c30d99445/91/page-frame.html");
//        request.addHeader("Host", "cloud.cn2030.com");
//        request.addHeader("Connection", "keep-alive");
//        request.addQuery("username", "foo");  // 添加URL的Query参数
        // 继续执行请求返回true
        return true;
    }

    /**
     * 该方法在请求成功响应时被调用
     */
    @Override
    public void onSuccess(Object data, ForestRequest request, ForestResponse response) {
        // 执行成功接收响应后处理的代码
        System.out.println("执行成功接收响应后处理 = " + data);

    }

    /**
     * 该方法在请求发送失败时被调用
     */
    @Override
    public void onError(ForestRuntimeException ex, ForestRequest request, ForestResponse response) {
        // 执行发送请求失败后处理的代码
        throw new BaseException(500, "发送错误");
    }

    /**
     * 该方法在请求发送之后被调用
     */
    @Override
    public void afterExecute(ForestRequest request, ForestResponse response) {
        Object result = response.getResult();
        if(result instanceof User) {
            System.out.println("hello world");
        }

        // 执行在发送请求之后处理的代码
    }
}
